from django.db import models
from django.db.models import signals 
from apscheduler.scheduler import Scheduler
from httplib import HTTPConnection

sched = Scheduler()

def jboss_instance_created(sender, instance, created, raw, **kwargs):
    from jboss_memory_analyzer.analyzer.views import jboss_instances
    #TODO update case and delete case
    if created == True :
        jboss_instances[instance.pk] =  instance
        sched.add_interval_job(createReport, minutes=instance.track_period,args=[instance.pk]) 

def createReport(instanceId):
    from jboss_memory_analyzer.analyzer.views import jboss_instances
    import time 
    conn = HTTPConnection(jboss_instances[instanceId].jmx_page, timeout=1000)
    conn.request("GET", "/jmx-console/HtmlAdaptor?action=invokeOpByName&name=jboss.system%3Atype%3DServerInfo&methodName=listMemoryPools&argType=boolean&arg0=True")
    #TODO proxy settings
    j_inst=Jboss_Instance()
    j_inst.pk=instanceId
    r1 = conn.getresponse().read().splitlines()
    for l in r1:
        if l.find('Total Memory Pools') != -1 :
            report=Report()
            report.report_date=time.time()
            print l
            l=l.replace("-", "")
            l=l.replace("/", "")
            l=l.replace(" ", "")
            l=l.split("<b>")
            #TODO sayilari check et ve refactor et burayi
            maxx=l[4].split("max")[3].split(":")[1]
            used=l[4].split("max")[3].split(":")[2]
            
            maxx=formatVal(maxx[0:maxx.index("<")])
            used=formatVal(used[0:used.index("<")])
            
            report.jboss_instance=j_inst
            report.mem_max_1=maxx
            report.mem_cur_1=used
            
            maxx=l[6].split("max")[3].split(":")[1]
            used=l[6].split("max")[3].split(":")[2]
            
            maxx=formatVal(maxx[0:maxx.index("<")])
            used=formatVal(used[0:used.index("<")])
            
            report.mem_max_2=maxx
            report.mem_cur_2=used
            
            maxx=l[8].split("max")[3].split(":")[1]
            used=l[8].split("max")[3].split(":")[2]
            
            maxx=formatVal(maxx[0:maxx.index("<")])
            used=formatVal(used[0:used.index("<")])
            
            report.mem_max_3=maxx
            report.mem_cur_3=used
            
            maxx=l[10].split("max")[3].split(":")[1]
            used=l[10].split("max")[3].split(":")[2]
            
            maxx=formatVal(maxx[0:maxx.index("<")])
            used=formatVal(used[0:used.index("<")])
            
            report.mem_max_4=maxx
            report.mem_cur_4=used
            
            maxx=l[12].split("max")[3].split(":")[1]
            used=l[12].split("max")[3].split(":")[2]
            
            maxx=formatVal(maxx[0:maxx.index("<")])
            used=formatVal(used[0:used.index("<")])
            
            report.mem_max_5=maxx
            report.mem_cur_5=used
            
            report.save()
                
            print maxx,used
    conn.close()
    

def formatVal(v):
    
    v=v.replace(",", ".")
    v=v.replace("Mb", "")
    v=v.replace("b", "")
    
    try:
        if v.index("Gb") > 0 :
            v=float(v.split("Gb")[0])*1024
            return v
    except ValueError:
        ''
    
    try:
        if v.index("Kb") > 0:
            v=float(v.split("Kb")[0])/1024
            return v
    except ValueError:
        ''
        
    try:
        if v.index("K") > 0:
            v=float(v.split("K")[0])/1024
            return v
    except ValueError:
        ''

    return v
        
class Jboss_Instance(models.Model):
    name = models.CharField(max_length=200)
    jmx_page = models.CharField(max_length=200)
    created_date = models.DateField(auto_now=True, auto_now_add=True)
    track_period=models.IntegerField()
    def __unicode__(self):
        return self.name
    
signals.post_save.connect(jboss_instance_created, Jboss_Instance, dispatch_uid="jboss_memory_analyzer.analyzer.models")  

    
class Report(models.Model):
    jboss_instance = models.ForeignKey(Jboss_Instance)
    report_date = models.CharField(max_length=20)
    mem_cur_1 = models.CharField(max_length=20)
    mem_max_1 = models.CharField(max_length=20)
    mem_cur_2 = models.CharField(max_length=20)
    mem_max_2 = models.CharField(max_length=20)
    mem_cur_3 = models.CharField(max_length=20)
    mem_max_3 = models.CharField(max_length=20)
    mem_cur_4 = models.CharField(max_length=20)
    mem_max_4 = models.CharField(max_length=20)
    mem_cur_5 = models.CharField(max_length=20)
    mem_max_5 = models.CharField(max_length=20)
    def __unicode__(self):
        return self.report_date